
tinymce.PluginManager.add('catalogue', function(editor, url){

    editor.ui.registry.addButton('catalogue', {
        icon: 'toc',
        tooltip: '生成目录',
        onAction: ()=>{
            initJstree();
        },
        onSetup: ()=>{
            initJstree();
        }
    });

    const initJstree = () => {
        var rootId = "-1";
        var data = [{"id" : rootId, "parent" : "#", "text" : "工作内容", "icon" : "glyphicon glyphicon-file", "state" : { "opened" : true}}];
        if (tinymce.activeEditor) {
            var $html = $(tinymce.activeEditor.getContent());
            var level1Id, level2Id;
            $html.each((i, obj) => {
                var $obj = $(obj);
                if ($(obj).hasClass("mce-paragraph")) {
                    var id = $obj.attr("id");
                    var level = $obj.attr("data-mce-level");
                    var text = $obj.text().replace("{*","").replace("*}","");
                    var parent;
                    if (level === "1") {
                        level1Id = id;
                        level2Id = null;
                        parent = rootId;
                    } else if (level === "2") {
                        level2Id = id;
                        parent = level1Id || rootId;
                    } else if (level === "3") {
                        parent = level2Id || level1Id || rootId;
                    }
                    data.push({"id" : id, "parent" : parent + '', "text" : text, "state" : { "opened" : true}});
                }
            });
        }
        $('#jstree').jstree('destroy');
        $('#jstree').data('jstree', false).empty();
        $('#jstree').on('select_node.jstree', function (e, data) {
            var id = data.node.id;
            var dom = tinymce.activeEditor.dom.get(id);
            dom && dom.scrollIntoView({
                behavior: 'smooth',
            });
        }).jstree({ 'core' : {
            'data' : data,
            'themes':{
                'icons' : false,
                'theme' : 'default',
                'dots' : true,
                'ellipsis': true,
                'stripes': false
            },
        }});
    }

    return {
        getMetadata: function () {
          return  {
            name: "catalogue",//插件名称
            url: "http://exampleplugindocsurl.com", //作者网址
          };
        }
    };

})